# coding=utf-8
from playwright.sync_api import sync_playwright
import time
import json
from update_auth_info import huadonyanzhen
from retrying import retry
import math
import random
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
from urllib import parse
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

inst_code_dict = {'XHHG': (r'42264', r'Xhhg2019@'), 'XH': (
    '12420000420007938Y', 'Whxh@85755457'), 'WB': ('13283766953', 'Ws123456+++')}


@retry(stop_max_attempt_number=3)
def update_pss_auth(inst):
    # 登录专利检索及分析网站 https://pss-system.cponline.cnipa.gov.cn/，更新登录信息
    print('开始更新专利登录状态')
    user, passwd = inst_code_dict.get(inst)
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=False)
        # browser = p.firefox.launch()
        context = browser.new_context(
            base_url='https://pss-system.cponline.cnipa.gov.cn/api', ignore_https_errors=True)
        context.set_default_timeout(60000)
        context.set_default_navigation_timeout(60000)
        page = context.new_page()
        huadonyanzhen(page, inst)
        page.goto('https://pss-system.cponline.cnipa.gov.cn/conventionalSearch')
        page.wait_for_load_state()
        page.click('xpath=//span[contains(text(),"同意")]/..')
        page.wait_for_timeout(1000)
        page.goto(
            'https://pss-system.cponline.cnipa.gov.cn/seniorSearch')
        page.wait_for_load_state()
        page.wait_for_timeout(5000)
        refresh_s = True
        while refresh_s:
            page.goto(
                'https://pss-system.cponline.cnipa.gov.cn/seniorSearch')
            page.wait_for_load_state()
            page.wait_for_timeout(5000)
            if page.title() == '高级检索':
                refresh_s = False
                print('@@已跳转到高级检索页面@@')
        el = page.locator('xpath=//span[text()="高级检索"]')
        el.wait_for(timeout=0)
        page.wait_for_timeout(5000)
        storage_state_path = f'./auth/{inst}_pss_state.json'
        storage = context.storage_state(path=storage_state_path)
        print(f'@@{inst}_账号登录信息保存到本地@@')


def get_key():
    # 生成加密密钥
    key_list = []
    e = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
         "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ".", "?", "~", "!", "@", "#", "$", "%", "^", "&", "*"]
    for i in range(16):
        n = math.ceil(random.random() * 46)
        key_list.append(e[n])
    key = ''.join(key_list)
    public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJyQCGUo+5Hg1dtOjzXC5GTUlWgiVg2UggYlPSgM4fE39wfJ3qJWOLYKSzGxpLhZtBSbMBJfJja60nSLdBJpAKcCAwEAAQ=="
    rsa_key = RSA.import_key(base64.b64decode(public_key))  # 导入读取到的公钥
    cipher = PKCS1_v1_5.new(rsa_key)                        # 生成对象
    cipher_text = base64.b64encode(
        cipher.encrypt(key.encode(encoding="utf-8")))
    encrypted_key = cipher_text.decode('utf8')
    return([key, encrypted_key])


def jiami_words(aes_str, key):
    # 使用ECB模式加密
    MODE = AES.MODE_ECB
    # 使用默认的pkcs7 padding
    PAD_STYLE = 'pkcs7'
    ENCODING = 'UTF-8'
    # key = "$#PATENT$@DRjt@!" 加密密钥由get_key函数生成
    aes = AES.new(key.encode('utf-8'), AES.MODE_ECB)  # 加密密钥
    pad_pkcs7 = pad(aes_str.encode('utf-8'), AES.block_size, style='pkcs7')
    encrypt_aes = aes.encrypt(pad_pkcs7)
    encrypted_text = str(base64.encodebytes(
        encrypt_aes), encoding='utf-8')  # 解码
    jiami_text = parse.quote(encrypted_text, 'utf-8')
    new_jiami_text = f'AES({jiami_text})'
    return(new_jiami_text)


if __name__ == '__main__':
    # inst_dict = {'XHHG': '信合红谷接口查询', 'XH': '协和端口查询', 'WB': "外部接口查询"}
    inst = 'XHHG'
    print(f'@@@开始更新{inst}登录信息@@@')
    update_pss_auth(inst)
